[8.x] Fix fail to morph with custom casting to objects #35420
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
While Laravel introduce custom cast in 7.x, it's not really that compatible with morph map.
For a
morphTo
relation to work, it relies on accessing the actual data with the__get()
method of the model to assume whether we're or not eager loading the relationship. See code here.By using the
__get()
method of the model, we'll be applying the cast to the attribute we're asking for. This works great before custom cast are introduced.However if a custom cast is applied on the attribute, the attribute might be casted to any object, which is incompatible with
Relation::morphMap()
(returning an array with the key asint/string
).Here's an example setup:
The
morphMap
above uses the keys of an array as the custom polymorphic types to map to the correspond models, which is impossible to map while the magic__get
method inModel.php
will be always casting it to aLogRole
object inmorphTo
.Sorry this is my first pull request to Laravel, I've tried my best to understand the contribution guide and explain my problem, please feel free to ask any question and I'll try my best to reply as soon as possible.